
const crypto = require('crypto');
const NodeJSEncrypt = require('node-jsencrypt');
/**
 * Base64编码
 * @param {string} txt - 待编码的文本
 * @returns {string} 编码后的文本
 */
export function encodeByBase64(txt) {
  if (typeof txt !== 'string') return ''
  return crypto.enc.Base64.stringify(crypto.enc.Utf8.parse(txt))
}

/**
 * Base64解码
 * @param {string} txt - 待解码的文本
 * @returns {string} 解码后的文本
 */
export function decodeByBase64(txt) {
  if (typeof txt !== 'string') return ''
  return crypto.enc.Utf8.stringify(crypto.enc.Base64.parse(txt))
}

/**
 * MD5加密
 * @param {string} txt - 待加密的文本
 * @returns {string} MD5加密后的文本
 */
export function encryptByMd5(txt) {
  if (typeof txt !== 'string') return ''
  return crypto.MD5(txt).toString()
}

const publicKey
  = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM51dgYtMyF+tTQt80sfFOpSV27a7t9u'
  + 'aUVeFrdGiVxscuizE7H8SMntYqfn9lp8a5GH5P1/GGehVjUD2gF/4kcCAwEAAQ=='

export function encryptByRsa(txt) {
  try {
    if (!txt) return ''
    const encryptor = new NodeJSEncrypt()
    encryptor.setPublicKey(publicKey)
    const encrypted = encryptor.encrypt(txt)
    if (!encrypted) throw new Error('RSA加密失败')
    return encrypted
  } catch (error) {
    console.error('RSA加密错误:', error)
    throw error
  }
}

export default encryptByRsa

const defaultKeyWork = 'XwKsGlMcdPMEhR1B'

export function encryptByAes(word, keyWord = defaultKeyWork) {
  try {
    if (!word) return ''
    const key = CryptoJS.enc.Utf8.parse(keyWord)
    const arcs = CryptoJS.enc.Utf8.parse(word)
    const encrypted = CryptoJS.AES.encrypt(arcs, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    })
    return encrypted.toString()
  } catch (error) {
    console.error('AES加密错误:', error)
    throw error
  }
}

/**
 * AES解密
 * @param {string} word - 待解密的文本
 * @param {string} keyWord - 密钥，默认使用defaultKeyWork
 * @returns {string} 解密后的文本
 */
export function decryptByAes(word, keyWord = defaultKeyWork) {
  try {
    if (!word) return ''
    const key = CryptoJS.enc.Utf8.parse(keyWord)
    const decrypted = CryptoJS.AES.decrypt(word, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return decrypted.toString(CryptoJS.enc.Utf8)
  } catch (error) {
    console.error('AES解密错误:', error)
    throw error
  }
}